package com.xixing.weixin.web;

import com.xixing.weixin.domain.Account;
import com.xixing.weixin.domain.School;
import org.springframework.roo.addon.web.mvc.controller.scaffold.RooWebScaffold;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

@RequestMapping("/accounts")
@Controller
@RooWebScaffold(path = "accounts", formBackingObject = Account.class)
public class AccountController {
    @RequestMapping(params = "weixin", method = RequestMethod.POST, produces = "text/html")
    public String createPhone(@Valid Account account, BindingResult bindingResult, Model uiModel, HttpServletRequest httpServletRequest) {
        if (bindingResult.hasErrors()) {
            populateEditForm(uiModel, account);
            return "accounts/create-phone";
        }
        uiModel.asMap().clear();
        account.persist();
        return "redirect:/accounts/" + encodeUrlPathSegment(account.getId().toString(), httpServletRequest) + "?weixin=" + account.getSchool().getWeixinCode();
    }

    // accounts?form&weixin=1234&schoolWeixin=school
    @RequestMapping(params = {"form", "weixin"}, produces = "text/html")
    public String createFormPhone(@RequestParam("schoolWeixin") String schoolWeixin,@RequestParam("weixin") String weixin, Model uiModel) {
        School school = School.findSchoolsByWeixinCode(schoolWeixin).getSingleResult();
        Account account = new Account();
        account.setSchool(school);
        account.setWeixinCode(weixin);
        populateEditForm(uiModel, account);
        return "accounts/create-phone";
    }

    @RequestMapping(params = "weixin", value = "/{id}", produces = "text/html")
    public String showPhone(@PathVariable("id") Long id, Model uiModel) {
        uiModel.addAttribute("account", Account.findAccount(id));
        uiModel.addAttribute("itemId", id);
        return "accounts/show-phone";
    }
}
